package helexis.game.tyrian.service;

import helexis.game.tyrian.Tyrian;

import java.util.HashMap;
import java.util.Map;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.utils.Disposable;

public class SoundManager implements Disposable {
	
	
	public enum TyrianSound {
		
		CLICK("sound/click.wav");
		
		private String fileName;
		
		private TyrianSound(String fileName) {
			this.fileName = fileName;
		}//end of constructor
		
		public String getFileName() {
			return this.fileName;
		}//end of getFileName()
		
	}//end of inner-enum TyrianSound
	
	
	public SoundManager() {
		
	}//end of constructor
	
	
	/**
	 * 사운드 볼륨
	 */
	private float volume = 1f;
	
	/**
	 * 사운드 활성화 여부
	 */
	private boolean enabled = true;
	
	/**
	 * 사운드 맵
	 */
	private Map<TyrianSound, Sound> sounds = new HashMap<TyrianSound, Sound>();
	
	
	/**
	 * 주어진 사운드를 플레이 합니다.
	 * 
	 * @param sound TyrianSound
	 */
	public void play(TyrianSound sound) {
		
		if (!this.enabled) {
			return;
		}//end if
		
		Gdx.app.log(Tyrian.LOG, "Playing sound : " + sound.name());
		
		Sound s = null;
		
		if (!this.sounds.containsKey(sound)) {
			this.sounds.put(sound, Gdx.audio.newSound(Gdx.files.internal(sound.getFileName())));
		}//end if
		
		s = this.sounds.get(sound);
		s.play(this.volume);
		
	}//end of play()
	
	
	/**
	 * 사운드 볼륨을 설정합니다.
	 * 
	 * @param volume 볼륨
	 */
	public void setVolume(float volume) {
		
		Gdx.app.log(Tyrian.LOG, "Adjusting sound volume to : " + volume);
		
		/*
		 * 경계 조건 컨트롤
		 * 
		 * Exception 을 발생시키는 것 보다는 그냥 최대/최소 값으로 설정함
		 */
		
		if (0 > volume) {
			this.volume = 0;
		} else if (1f < volume) {
			this.volume = 1f;
		} else {
			this.volume = volume;
		}//end if else
		
	}//end of setVolume()
	
	
	/**
	 * 사운드 볼륨을 설정합니다.
	 * 
	 * @param enabled 사운드 볼륨
	 */
	public void setEnabled(boolean enabled) {
		
		Gdx.app.log(Tyrian.LOG, "Turn off sound...");
		
		this.enabled = enabled;
		
	}//end of setEnabled()


	@Override
	public void dispose() {
		
		Gdx.app.log(Tyrian.LOG, "Disposing SoundManager...");
		
		for (Sound s : this.sounds.values()) {
			s.stop();
			s.dispose();
		}//end for
		
	}//end of dispose()
	

}
//end of SoundManager.java